package org.mx.service.server.jmx;

import java.util.Date;

import org.mx.DateUtils;
import org.mx.service.server.HttpServerConfigBean;
import org.mx.service.server.HttpServerFactory;

/**
 * Web服务器MXBean实现类
 * @author john.peng
 *
 */
public class HttpServer implements HttpServerMXBean {
	/**
	 * 服务器配置对象，可能是WebServerConfigBean, WebsocketServerConfigBean, RestfulServerConfigBean, ServletServerConfigBean等
	 */
	protected HttpServerConfigBean configBean;
	private long startedTime = -1L;
	/**
	 * 服务器工厂，可能是WebServerFactory, WebsocketServerFactory, RestfulServerFactory, ServletServerFactory等
	 */
	protected HttpServerFactory httpServerFactory;

	/**
	 * 构造函数
	 * @param configBean Http服务器配置信息对象
	 */
	public HttpServer(HttpServerConfigBean configBean) {
		super();
		this.configBean = configBean;
	}

	/**
	 * 设置服务器工厂
	 * @param httpServerFactory 服务器工厂
	 */
	public void setHttpServerFactory(HttpServerFactory httpServerFactory) {
		this.httpServerFactory = httpServerFactory;
	}

	/**
	 * 设置Web服务器启动成功标志
	 */
	public void serverStarted() {
		startedTime = System.currentTimeMillis();
	}

	@Override
	public boolean isEnabled() {
		return configBean != null ? configBean.isEnabled() : false;
	}

	@Override
	public int getPort() {
		return configBean != null ? configBean.getPort() : 0;
	}

	@Override
	public void setPort(int port) {
		if (configBean != null) {
			configBean.setPort(port);
		}
	}

	@Override
	public int getMaxThreads() {
		return configBean != null ? configBean.getThreads() : 0;
	}

	@Override
	public String getStartedTime() {
		return DateUtils.get23Date(new Date(startedTime));
	}

	/**
	 * 将运行持续时间转换为“#天#小时#分#秒”的格式。
	 * @param time 运行持续时间
	 * @return 时间描述
	 */
	private String format(long time) {
		int[] units = { 60, 60, 24 };
		int[] number = { 0, 0, 0, (int) (time / 24 / 3600) };
		time -= number[3] * 24 * 3600;
		String[] names = { "秒", "分", "小时", "天" };
		for (int index = 0; index < 3; index++) {
			number[index] = (int) (time % units[index]);
			time = (time - number[index]) / units[index];
		}
		StringBuffer sb = new StringBuffer();
		for (int index = 3; index >= 0; index--) {
			if (number[index] > 0) {
				sb.append(number[index]);
				sb.append(names[index]);
			}
		}
		return sb.toString();
	}

	@Override
	public String getElapseTime() {
		long time = System.currentTimeMillis() - startedTime;
		time = Math.max(time, 0);
		return format(time / 1000);
	}

	@Override
	public void startServer() throws Exception {
		if (httpServerFactory != null && httpServerFactory.getServer().isStopped()) {
			httpServerFactory.init();
		}
	}

	@Override
	public void stopServer() throws Exception {
		if (httpServerFactory != null && httpServerFactory.getServer().isStarted()) {
			httpServerFactory.destroy();
		}
	}

	@Override
	public void restartServer() throws Exception {
		stopServer();
		startServer();
	}

}
